package com.zrrd._11_network.udp.no_01;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * @author WanJl
 * @version 1.0
 * @title Send
 * @description 发送端
 * @create 2023/10/28 21:33
 */
public class Send {
    public void sendData() {
        DatagramSocket ds = null;
        System.out.println("请输入接收端ip：");
        //1、创建Scanner对象，控制键盘输入
        Scanner sc = new Scanner(System.in);
        String address = sc.nextLine();
        System.out.println("请输入接收端端口号：");
        String portStr = sc.nextLine();
        int port = Integer.parseInt(portStr);

        while (true) {
            try {
                System.out.println("请输入您要发送的信息....");
                String content = sc.nextLine();

                //2、创建DatagramSocket建立虚拟链路
                ds = new DatagramSocket();
                //3、创建DatagramPacket将数据转换成字节数组然后封装到数据包
                byte[] bys = content.getBytes();
                DatagramPacket datagramPacket = new DatagramPacket(bys, bys.length, InetAddress.getByName(address), port);
                //4、发送数据包
                ds.send(datagramPacket);

                if (content.equals("886")) {
                    System.out.println("数据发送结束...");
                    break;
                }
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //4、关闭发送端Socket
                ds.close();
            }
        }
    }
}
